package com.hy.admin.controller;

import com.aliyuncs.exceptions.ClientException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hy.admin.helper.request.AccountRequest;
import com.hy.core.request.ApiRequestDTO;
import com.hy.core.response.ApiResponseDTO;
import com.hy.utils.CommonUtility;
import com.hy.utils.SmsDemo;
import org.apache.commons.httpclient.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by shitou on 18/2/7.
 */
@RestController
@RequestMapping("/api/sms")
public class SmsController {
    protected final Logger logBase = LoggerFactory.getLogger(SmsController.class);

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public ApiResponseDTO send(@RequestBody final ApiRequestDTO apiRequestDTO) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        logBase.info("sms/send_request:{}", gson.toJson(apiRequestDTO));
        ApiResponseDTO apiResponseDTO = new ApiResponseDTO(HttpStatus.SC_OK, "", apiRequestDTO.getUuid());
        AccountRequest accountRequest = gson.fromJson(apiRequestDTO.getRequestData(), AccountRequest.class);
        String curSmsCode = CommonUtility.getSmsCode();
        boolean sendReuslt =false;
        try {
            sendReuslt = SmsDemo.sendSms(accountRequest.getMobile(), curSmsCode);
        }catch (ClientException e){
            logBase.error("",e);
            apiResponseDTO.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }
        if(sendReuslt) {
            SmsDemo.addCode(accountRequest.getMobile(), curSmsCode);
        }
        apiResponseDTO.setResponseData(sendReuslt ? "success" : "fail");
        logBase.info("sms/send_response:{}", gson.toJson(apiResponseDTO));
        return apiResponseDTO;
    }
}
